class WorkingHoursController < ApplicationController
  before_filter :account_required, :login_required, :find_user, :ignore_normal_users
  skip_before_filter :set_user_time_zone, :only => :create
  
  def index
    @hour = Hour.new
    Rails.cache.write("working_hours_#{@user.id}", Hour.find_all_by_user_id(@user.id, :order => 'date DESC'))
    @working_hours = Rails.cache.read("working_hours_#{@user.id}")
  end
  
  def new
    @hour = Hour.new
  end
  
  # Create hour
  def create
    @hours = []
    params[:hour] ||= []
    params[:hour].each do |hour|
      hour[:user_id] = @user.id
      @hours << Hour.new(hour) unless hour.empty?
    end
    if @hours.each(&:save)
      flash[:notice] = "Saved"
      redirect_to user_working_hours_path(params[:user_id])
    end
  end
  
  # Show hour
  def show
    @hour = @user.hours.find(params[:id])
  end
  
  # Search hours
  def search
    @search_engine = SearchHour.new(@user, params[:search])
    search_results = @search_engine.search(:order => 'date DESC', :include => :project)
    # Write to cache
    Rails.cache.write("working_hours_#{@user.id}", search_results)
    @working_hours = search_results
  end
  
  # Export hours in xls or pdf
  def export
    @export_info = params[:export_hours]
    @lounch_brake = params[:export_hours][:lounch_break].to_i.minutes.to_f
    set_headers
    @hours = Rails.cache.read("working_hours_#{@user.id}")
    
    # Set filename
    @filename = "#{@user.name}_#{@hours.last.date.to_s(:finnish_date)}-#{@hours.first.date.to_s(:finnish_date)}"
    headers['Content-Disposition'] = 'attachment; filename="' + @filename + '.xls"'
    
    @hours
    render :layout => false
  end
  
  # Manage working hours.
  # User can delete or confirm from the same form
  def manage_hours
    action = params[:confirmed].downcase.to_sym
    values = params[:hour_delete].select {|hour| hour.to_i != 0 }
    respond_to do |format|
      case action
        when :delete
          values.each {|id| Hour.find_by_id(id).destroy }
        when :confirm
          values.each {|id| Hour.find_by_id(id).confirm }
      end
      format.js do
        render :update do |page|
          
          # When action is delete
          values.each do |id| 
            page["work_hour_#{id}"].visual_effect :highlight
            page << "$('#work_hour_#{id}').fadeOut();"
          end if action == :delete
          
          # Action is confirm
          values.each do |id| 
            page["work_hour_#{id}"].visual_effect :highlight, :color => '#ccc'
            page.replace_html "verified_#{id}", "Verified"
          end if action == :confirm
        end
      end   
      format.html { redirect_to user_working_hours_path(@user) }
    end
  end
 
  # Destroy
  def destroy
    @hour = Hour.find(params[:id]).destroy
    redirect_to user_working_hours_path(@user)
  end
  
  private
  
  # Find user
  def find_user
    @user = User.find_by_id(params[:user_id], :conditions => ['company_id = ?', current_account.id])
    raise ActiveRecord::RecordNotFound, "Page not found" if @user.nil?
  end
  
  # Before filter for ignoring normal users
  def ignore_normal_users
    if logged_in?
      u = current_user
      unless u.id == @user.id or admin_required or superior_required
        flash[:error] = "Error"
        redirect_to user_path(u.id)
      end
    end
  end
  
  def set_headers
    headers['Content-Type'] = 'application/vnd.ms-excel'
    headers['Cache-Control'] = ''
  end
end
